<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2017 https://git.oschina.net/honoryao All rights reserved.
// +----------------------------------------------------------------------
// | Author: honoryao <2463523099@qq.com>-2017/8/17
// +----------------------------------------------------------------------
// | app\common\model-Section
// +----------------------------------------------------------------------

/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/8/17
 * Time: 15:05
 */

namespace app\common\model;


use think\Model;
use think\Validate;
class Section extends Model
{
    protected $autoWriteTimestamp = true;
    public function checkform($post)
    {
        // 数据验证
        $validate = new Validate([
            'name|部门名称' => 'require',
            'is_copy|是否抄送' =>  'require|in:1,2',
            'copy_name|抄送邮箱' =>  ['regex'=>'/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,6})+$/'],
        ],['copy_name.regex'=>'抄送邮箱格式错误']);

        if (!$validate->check($post)) {
            $retArray = ['rel' => 0, 'msg' => $validate->getError()];
            return $retArray;
        }else {
            return false;
        }
    }

    public function addSection($post)
    {
        $res = $this->checkForm($post);
        if ($res) {
            return $res;
        }
        if($post['is_copy']==1){
            if(empty($post['copy_name'])){
                $msg['rel'] = 0;
                $msg['msg']  = '抄送邮箱为空';
                return $msg;
            }
            if(empty($post['send_name'])){
                $msg['rel'] = 0;
                $msg['msg']  = '抄送人姓名为空';
                return $msg;
            }
        }else{
            $post['copy_name']='';
            $post['send_name']='';
        }
        if (isset($post['id'])&&!empty($post['id'])) {//编辑
            $addinfo = $this->allowField(true)->isUpdate(true)->save($post,['id'=>$post['id']]);
        }else{//新增
            $post['add_uname']=session('username');
            $addinfo = $this->allowField(true)->isUpdate(false)->save($post);
        }
        if ($addinfo){
            $msg['rel'] = 1;
            $msg['msg']  = '保存成功';
        }else{
            $msg['rel'] = 0;
            $msg['msg']  = '保存失败';
        }
        return $msg;
    }
}